package com.app.mycoffee2_1.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.mycoffee2_1.MainActivity;
import com.app.mycoffee2_1.R;
import com.app.mycoffee2_1.adapter.ShoppingCartAdapter;
import com.app.mycoffee2_1.api.Api;
import com.app.mycoffee2_1.api.ApiConfig;
import com.app.mycoffee2_1.api.CoffeeCallback;
import com.app.mycoffee2_1.api.Util;
import com.app.mycoffee2_1.manager.LoginInfoManager;
import com.app.mycoffee2_1.model.Order;
import com.app.mycoffee2_1.model.OrderItem;
import com.app.mycoffee2_1.model.Result;
import com.app.mycoffee2_1.model.ShoppingCart;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import okhttp3.FormBody;

public class ShoppingCartFragment extends BaseFragment {
    private TextView title;
    private RecyclerView recyclerView;

    private List<ShoppingCart> shoppingCarts = new ArrayList<>();
    public static ShoppingCartAdapter shoppingCartAdapter;
    private Button buy_btn;
    private TextView tv_sum_price;
    static BigDecimal totalPrice = new BigDecimal("0");
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                shoppingCartAdapter.setShoppingCarts(shoppingCarts);
                shoppingCartAdapter.notifyDataSetChanged();
            }
        }
    };

    public ShoppingCartFragment() {
    }

    public static ShoppingCartFragment newInstance() {
        return new ShoppingCartFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    protected void initView() {
        title = mRootView.findViewById(R.id.title);
        recyclerView = mRootView.findViewById(R.id.shopping_cart_lv);
        tv_sum_price = mRootView.findViewById(R.id.sum_price_tv);
        buy_btn = mRootView.findViewById(R.id.buy_btn);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        // set layout manager
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        buy_btn.setOnClickListener(new MyBtnClickListener());
        title.setText("购物车");
        HashMap<String, Object> params = new HashMap<>();
        params.put("userId", LoginInfoManager.getInstance().getUserId(Objects.requireNonNull(getActivity())));
        for (ShoppingCart sc:shoppingCarts){
            if (sc.getIsSelected()){
                totalPrice = totalPrice.add(Util.multiply(sc.getProductPrice(), sc.getNum()));
            }
        }
        tv_sum_price.setText(totalPrice.toString());

        shoppingCartAdapter = new ShoppingCartAdapter(Objects.requireNonNull(getActivity()),
                new ShoppingCartAdapter.OnItemBtnClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onCheckBtnClick(int position) {
                        ShoppingCart sc = shoppingCarts.get(position);
                        Toast.makeText(getActivity(), "点击选中或不选中", Toast.LENGTH_SHORT).show();
                        if (sc.getIsSelected()){
                            totalPrice = totalPrice.add(Util.multiply(sc.getProductPrice(), sc.getNum()));
                        }else {
                            totalPrice = totalPrice.subtract(Util.multiply(sc.getProductPrice(), sc.getNum()));
                        }
                        tv_sum_price.setText(totalPrice.toString());
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onMinusBtnClick(int position) {
                        Toast.makeText(getActivity(), "点击数量减少", Toast.LENGTH_SHORT).show();
                        ShoppingCart sc = shoppingCarts.get(position);
                        if (sc.getNum()!=1){
                            shoppingCarts.get(position).setNum(sc.getNum()-1);
                            if (sc.getIsSelected()){
                                totalPrice = totalPrice.subtract(Util.multiply(sc.getProductPrice(), 1));
                                tv_sum_price.setText(totalPrice.toString());
                            }
                        }
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onAddBtnClick(int position) {
                        Toast.makeText(getActivity(), "点击数量增加", Toast.LENGTH_SHORT).show();
                        ShoppingCart sc = shoppingCarts.get(position);
                        shoppingCarts.get(position).setNum(sc.getNum()+1);
                        if (sc.getIsSelected()){
                            totalPrice = totalPrice.add(Util.multiply(sc.getProductPrice(), 1));
                            tv_sum_price.setText(totalPrice.toString());
                        }
                    }
                });
        recyclerView.setAdapter(shoppingCartAdapter);
        getAllShoppingCarts(getActivity(), params);
    }

    public class MyBtnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            showToast("点击了购买的按钮");

            List<OrderItem> orderItems = new ArrayList<>();
            List<Long> scIds = new ArrayList<>();
            for (ShoppingCart sc:shoppingCarts){
                if (sc.getIsSelected()){
                    OrderItem orderItem = new OrderItem();
                    orderItem.setGoodsId(sc.getProductId());
                    orderItem.setGoodsName(sc.getProductName());
                    orderItem.setSellingPrice(Util.multiply(sc.getProductPrice(),sc.getNum()));
                    orderItem.setGoodsCount(sc.getNum());
                    orderItems.add(orderItem);
                    scIds.add(sc.getId());
                }
            }

            Order order = new Order();
            order.setUserId(LoginInfoManager.getInstance().getUserInfo(Objects.requireNonNull(getActivity())).getUserId());
            order.setTotalPrice(BigDecimal.valueOf(39.00));
            order.setItemVOList(orderItems);
            order.setSCIds(scIds);
            String orderJson = new Gson().toJson(order);
            FormBody formBody = new FormBody.Builder()
                    .add("orderJson", orderJson)
                    .build();
            addOrder(getActivity(),formBody);
            navigateToWithFlag(MainActivity.class, 2);
        }
    }

    public void getAllShoppingCarts(Context context, HashMap<String, Object> params){
        Api.config(ApiConfig.SHOPPING_CART_LIST_BY_USER, params).getRequest(context, new CoffeeCallback() {

            @Override
            public void onSuccess(String res) {
                Result<List<ShoppingCart>> result = new Gson().fromJson(res, new TypeToken<Result<List<ShoppingCart>>>(){}.getType());
                if (result.getResultCode()!=null&&result.getResultCode()==200){
                    shoppingCarts.removeAll(shoppingCarts);
                    shoppingCarts.addAll(result.getData());
                    mHandler.sendEmptyMessage(2);
                }
                System.out.println(result.getMessage());
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println(e.toString());
            }
        });
    }

    public void addOrder(Context context, FormBody formBody){
        Api.config(ApiConfig.ORDER_ADD, formBody).postRequest(new CoffeeCallback() {
            @Override
            public void onSuccess(String res) {
                Result result = new Gson().fromJson(res, Result.class);
                if (result.getResultCode()!=null&&result.getResultCode()==200){
                    // TODO
                }
                System.out.println(result.getMessage());
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}
